package com.kaka.jsonmap.core;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JsonPreprocessor {

    public static String removeComments(String jsonWithComments) {
        if (jsonWithComments == null || jsonWithComments.trim().isEmpty()) {
            return jsonWithComments;
        }

        StringBuilder cleanedJson = new StringBuilder();
        String[] lines = jsonWithComments.split("\n");

        for (String line : lines) {
            String trimmedLine = line.trim();
            if (trimmedLine.isEmpty()) {
                cleanedJson.append(line).append("\n");
                continue;
            }

            // 处理独立行注释
            if (trimmedLine.startsWith("//")) {
                log.debug("Removed standalone comment line: {}", trimmedLine);
                cleanedJson.append(line.substring(0, line.indexOf(trimmedLine))).append("\n"); // 保留缩进
                continue;
            }

            // 处理文本末尾注释
            int commentIndex = findCommentIndex(trimmedLine);
            if (commentIndex != -1) {
                String cleanLine = trimmedLine.substring(0, commentIndex).trim();
                if (!cleanLine.isEmpty()) {
                    // 保留原始缩进
                    int originalIndex = line.indexOf(cleanLine);
                    cleanedJson.append(line.substring(0, originalIndex + cleanLine.length())).append("\n");
                    log.debug("Removed inline comment from: {}", line.trim());
                } else {
                    cleanedJson.append(line.substring(0, line.indexOf(trimmedLine))).append("\n");
                }
            } else {
                cleanedJson.append(line).append("\n");
            }
        }

        return cleanedJson.toString().trim();
    }

    private static int findCommentIndex(String line) {
        int commentIndex = line.indexOf("//");

        // 未找到注释
        if (commentIndex == -1) {
            return -1;
        }

        // 检查注释是否在字符串内
        int quoteCount = 0;
        for (int i = 0; i < commentIndex; i++) {
            if (line.charAt(i) == '"') {
                if (i == 0 || line.charAt(i - 1) != '\\') {
                    quoteCount++;
                }
            }
        }
        // 如果引号数量为奇数，说明注释在字符串内，不移除
        if (quoteCount % 2 != 0) {
            return -1;
        }

        return commentIndex;
    }
}